package com.haibeimohe;

import com.haibeimohe.config.JsonSerializer;
import com.haibeimohe.config.RpcDecoder;
import com.haibeimohe.config.RpcEncoder;
import com.haibeimohe.config.RpcRequest;
import com.haibeimohe.handler.UserServiceHandler;
import com.haibeimohe.util.ApplicationContextFactory;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

/**
 * 服务器启动类
 * @author hassan
 */
@SpringBootApplication
public class ServerBootStrap {

    public static void main(String[] args) throws InterruptedException {
        ApplicationContext context = SpringApplication.run(ServerBootStrap.class, args);
        ApplicationContextFactory.setApplicationContext(context);
        startServer("127.0.0.1", 8888);
    }

    private static void startServer(String ip, int port) throws InterruptedException {
        // 1.创建两个线程池对象
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        // 2.创建服务器的启动引导对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        // 3.配置启动引导类
        serverBootstrap.group(bossGroup, workGroup).channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        pipeline.addLast(new RpcEncoder(RpcRequest.class, new JsonSerializer()));
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new JsonSerializer()));
                        pipeline.addLast(new UserServiceHandler());
                    }
                });
        serverBootstrap.bind(ip, port).sync();
    }

}
